var OnFormSubmittion = function() {
  var form = this;
  var data = {};
  data[form.name] = {};
  for (var i = 0; i < form.length; ++i) {
    data[form.name][form[i].name] = form[i].value;
  }
  chrome.extension.sendRequest('RegisterNewPasswords');
}

var CollectPasswordForms = function() {
  var loading_url = chrome.extension.getURL('loading.gif');
  for (var i = 0; i < document.forms.length; ++i) {
    var form = document.forms[i];
    var password_present = false;
    for (var j = 0; j < form.length; ++j) {
      if (form[j].type.toLowerCase() == 'password') {
        form.addEventListener('submit', OnFormSubmittion, false);
        password_present = true;
      }
    }
    if (password_present) {
      for (var j = 0; j < form.length; ++j) {
        if (form[j].type.toLowerCase() == 'password' ||
            form[j].type.toLowerCase() == 'text') {
          form[j].style.backgroundImage = 'url(' + loading_url + ')';
          form[j].style.backgroundPosition = 'top right';
          form[j].style.backgroundRepeat = 'no-repeat';
          form[j].style.backgroundHeight = form[j].style.height;
        }
      }
    }
  }
}

var PopulatePasswordForms = function(data) {
  for (var i = 0; i < document.forms.length; ++i) {
    var form = document.forms[i];
    var form_data = data[form.name];
    for (var j = 0; j < form.length; ++j) {
      form[j].style.backgroundImage = '';
      if (form_data && form_data[form[j].name]) {
        form[j].value = form_data[form[j].name];
      }
    }
  }
}

CollectPasswordForms();
chrome.extension.sendRequest('GetPasswordsForPage', PopulatePasswordForms);
